package com.example.mq.demo;

import com.example.mq.client.Channel;
import com.example.mq.client.Connection;
import com.example.mq.client.ConnectionFactory;
import com.example.mq.common.Consumer;
import com.example.mq.common.MqException;
import com.example.mq.server.core.BasicProperties;
import com.example.mq.server.core.ExchangeType;

import java.io.IOException;

public class DemoConsumer {
    public static void main(String[] args) throws IOException, MqException, InterruptedException {
        System.out.println("启动消费者");
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("127.0.0.1");
        factory.setPort(9090);

        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        // 创建交换机和队列
        channel.exchangeDeclare("testExchange", ExchangeType.DIRECT, true, false, null);
        channel.queueDeclare("testQueue", true, false, false, null);
        // 订阅队列消息
        channel.basicConsume("testQueue", true, new Consumer() {
            @Override
            public void handleDelivery(String consumerTag, BasicProperties basicProperties, byte[] body) throws MqException, IOException {
                System.out.println("[消费数据]开始!");
                //System.out.println("consumerTag = " + consumerTag);
                System.out.println("basicProperties" + basicProperties);
                String bodyString = new String(body, 0, body.length);
                System.out.println("body = " + bodyString);
                System.out.println("[消费数据] 结束!");
            }
        });

        while(true) {
            Thread.sleep(500);
        }
    }
}
